package com.ocm.commerceinteraction.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.FriendsList;
import com.ocm.commerceinteraction.model.GroupMemberBean;
import com.ocm.commerceinteraction.model.UserModel;
import com.ocm.commerceinteraction.ui.adapter.XTContactAdapter;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.helper.StringHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.view.XTContactList;
import com.ocm.commerceinteraction.util.view.sortlist.CharacterParser;
import com.ocm.commerceinteraction.util.view.sortlist.PinyinComparator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import easeui.adapter.EaseContactAdapter;
import easeui.controller.EaseUI;
import easeui.domain.EaseUser;
import easeui.widget.EaseContactList;
import easeui.widget.EaseSidebar;

/**
 * Created by Curry on 2016-5-7.
 */
@EActivity(R.layout.activity_select_user)
public class SelectUserActivity extends BaseActivity {
    @ViewById(R.id.content_container)
    FrameLayout contentContainer;

    @ViewById(R.id.contact_list)
    EaseContactList easeContactList;
    @ViewById(R.id.search_clear)
    ImageButton clearSearch;
    @ViewById(R.id.query)
    EditText query;
    @ViewById(R.id.list)
    ListView listView;

    @ViewById(R.id.right_text_btn)
    TextView rightBtn;

    @ViewById(R.id.sidebar)
    EaseSidebar sidebar;
    @ViewById(R.id.toptitle_title)
    TextView topTitle;

    XTContactAdapter xtContactAdapter;

    @Extra("flag")
    String flag = "";

    @Extra("Group_uniq_id")
    String Group_uniq_id;



    @AfterViews
    void initView() {
        topTitle.setText("添加好友");
        rightBtn.setText("添加");
        rightBtn.setVisibility(View.VISIBLE);
        characterParser = CharacterParser.getInstance();
        loadData();

        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });

        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 隐藏软键盘
                hideSoftKeyboard();
                return false;
            }
        });
    }

        public void filter(CharSequence str) {
            xtContactAdapter.getFilter().filter(str);
        }

    private void loadData() {
        requestUrl = RequestAddr.serarchFriList;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //处理数据
    FriendsList friendsList;
    List<UserModel> userModelList = new ArrayList<>();
    private void dealData(Object object) {
        try {
            friendsList = GlobalApplication.gson.fromJson(object.toString(), FriendsList.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(this, baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        userModelList.clear();
        String[] date = new String[friendsList.getData().size()];
        for (int i = 0; i < friendsList.getData().size(); i++) {
            date[i] = friendsList.getData().get(i).getNick();
        }
        SourceDateList = filledData(date);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        userlist.clear();
        LogHelper.i("size:"+SourceDateList.size());
        for (int i = 0; i < SourceDateList.size(); i++) {
            for (int j = 0; j < friendsList.getData().size() ; j++) {
                if (friendsList.getData().get(j).getNick().equals(SourceDateList.get(i).getName())) {
                    EaseUser easeUser = new EaseUser(friendsList.getData().get(j).getNick());
                    easeUser.setInitialLetter(SourceDateList.get(i).getSortLetters());
                    easeUser.setSelect(false);
                    easeUser.setEid(friendsList.getData().get(j).getUser_uniq_id());
                    easeUser.setAvatar(friendsList.getData().get(j).getIcon());
                    easeUser.setUsername(friendsList.getData().get(j).getNick());
                    userlist.add(easeUser);
                    break;
                }
            }
        }
        xtContactAdapter = new XTContactAdapter(this,0,userlist, 1);
        listView.setAdapter(xtContactAdapter);
    }

    @ItemClick(R.id.list)
    void userItemClick(int position) {
        userlist.get(position).setSelect(!userlist.get(position).isSelect());
        xtContactAdapter.notifyDataSetChanged();
    }

    public static int RES_FRILIST = 001;
    @Override
    @Click({R.id.right_text_btn, R.id.back_btn})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.right_text_btn:
                String friendList = "";
                for (int i = 0; i < userlist.size(); i++) {
                    if (userlist.get(i).isSelect()){
                            friendList += "," +userlist.get(i).getEid();
                    }
                }
                if (flag.equals("invite")) {
                    invateHttp(friendList);
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("friendList", friendList);
                    setResult(RES_FRILIST, intent);
                    finish();
                }
            break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    void invateHttp(String friendList) {
        if (friendList.length() > 0) {
            friendList = friendList.substring(1);
        }
        requestUrl = RequestAddr.addGroupFriendRequest+
                "?group_uniq_id="+Group_uniq_id
                +"&keywords="+""
                +"&merbers="+friendList;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>(){
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
//                dealBaseData(o);
                dealInviteData(o);
            }


            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    BaseModel baseModel;
    void dealInviteData(Object object) {
        try {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
        }
        finish();
    }



    protected InputMethodManager inputMethodManager;
    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     *//**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<GroupMemberBean> SourceDateList;
    private List<EaseUser> userlist = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<GroupMemberBean> filledData(String[] date) {
        List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

        for (int i = 0; i < date.length; i++) {
            GroupMemberBean sortModel = new GroupMemberBean();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            if (pinyin.equals("")){
                pinyin = "#";
            }
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
}
